import java.io.File;
import java.io.FileOutputStream;

public class AISMA extends Scheduler implements Runnable {
	int start;
	int stop;
	byte[] BLOCK;
	int[] USERID;
	byte[] USERVOTE;

	public AISMA(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = String.format("%s%07d.bin", BLOCK_PATH, start);		File out = new File(FILE_NAME);
		FileOutputStream fos;
		
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Done writing: " + FILE_NAME + " @ "
				+ this.getClass());
	}

	@Override
	public void run() {
		System.out.print("Started working on block: " + start + " @ " + this.getClass() + " : ");
		
		this.USERID = new int[ITEMA.length];
		this.USERVOTE = new byte[ITEMA.length];
		
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];

		int c = 0;
		int tempItemID;
		
		for (int bUserID = start; bUserID < stop; bUserID++) {
			User aUser = USERA[bUserID];
			//Mark all items that were voted on by bUser
			for(int i=0; i<aUser.ilen; i++){
				tempItemID = aUser.items[i];
				USERID[tempItemID] = bUserID;
				USERVOTE[tempItemID] = aUser.votes[i];
			}
			
			for (int i = 0; i < ilen; i++) {
				int bItemID = USERB[bUserID].items[i];

				byte pred = predict(bUserID, bItemID);

				BLOCK[c * ilen + i] = pred;
			}
			c++;
		}

		writeBlock();
	}

	public byte predict(int bUserID, int bItemID) {
		Item aItem = ITEMA[bItemID];
		double tot = 700;
		int hit = 10;
		

		for (int historyUserID : aItem.users) {
			User historyUser = USERA[historyUserID];

			for (int linkedItemID : historyUser.items) {
				
				if (USERID[linkedItemID] == bUserID) {
					tot += USERVOTE[linkedItemID];
					hit++;
				}
			}
		}

		return (byte) (tot / hit);
	}
}
